import { _decorator, Component, instantiate, Node, Prefab } from 'cc';
import { CardItemController } from 'db://assets/scripts/card/CardItemController';
import { DataManager } from 'db://assets/scripts/DataManager';
const { ccclass, property } = _decorator;

@ccclass('CardController')
export class CardController extends Component {
  @property(Prefab)
  cardItemPrefab: Prefab = null;

  cardItemCList: CardItemController[] = [];
  position: -1 | 1 = -1; // 1当前客户端 -1对方客户端

  start() {}

  init({ cardList, position }: any = {}) {
    this.position = position;
    // 清理原来的card
    this.cardItemCList = [];
    this.node.children.forEach((child: Node) => {
      child.destroy();
    });
    // 新建card
    cardList.forEach((card: any) => {
      const cardItem = instantiate(this.cardItemPrefab);
      cardItem.parent = this.node;
      const cardItemC = cardItem.getComponent(CardItemController);
      cardItemC.init({
        ...card,
        position: this.position,
      });
      this.cardItemCList.push(cardItemC);
    });
  }

  // 选择一张卡片
  selectCard(cardIndex: number) {
    this.cardItemCList.forEach((cardItemC: CardItemController) => {
      if (cardItemC.cardIndex.string === cardIndex.toString()) {
        cardItemC.select();
      } else {
        cardItemC.unSelect();
      }
    });
  }

  // 标记为已使用
  markCardUsed(cardIndex: number) {
    this.cardItemCList.forEach((cardItemC: CardItemController) => {
      if (cardItemC.cardIndex.string === cardIndex.toString()) {
        cardItemC.markCardUsed();
      }
    });
  }

  update(deltaTime: number) {
    const { gameData, role } = DataManager.instance;
    if (gameData) {
      const { cards, selectedCard } =
        gameData.clients.find((client: any) => {
          if (this.position === 1) {
            return client.role === role;
          } else {
            return client.role !== role;
          }
        }) ?? {};
      if (cards) {
        this.cardItemCList.forEach((cardItemC: CardItemController, index) => {
          cards[index].dark ? cardItemC.setDark() : cardItemC.setUnDark();
        });
      }
      if (cards && selectedCard) {
        // 选择手牌
        this.selectCard(selectedCard);
        cards.forEach((card: any) => {
          // 标记为已使用
          if (card.used && !gameData.settlement)
            this.markCardUsed(card.cardIndex);
        });
      }
    }
  }
}
